﻿using InventoryIssue.API.Write.Application.Command.Allocate;
using InventoryIssue.Domain;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;

namespace InventoryIssue.API.Write.Application.Handler.Allocate
{
    public class ApprovalAllocateHandler:IRequestHandler<ApprovalAllocateCommand ,APIResult<int>>
    {

        DatabaseContext db;

        public ApprovalAllocateHandler(DatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(ApprovalAllocateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 初始化返回结果
                APIResult<int> result = new APIResult<int>();

               

                // 查询调拨单信息
                var allocate = await db.SqlSugar.Queryable<AllocateModel>()
                    .Where(x => x.AllocateId == request.AllocateId)
                    .FirstAsync();

                // 验证调拨单是否存在
                if (allocate == null)
                {
                    result.Message = $"未找到调拨单，AllocateId: {request.AllocateId}";
                    result.Code = APIEnum.Fail;
                    return result;
                }

                // 开始数据库事务
                await db.SqlSugar.Ado.BeginTranAsync();

                // 更新主表字段 - 只允许编辑非主键字段
                // allocate.AllocateId = request.AllocateId; // 禁止编辑主键字段
                
                if (request.State >= 0)
                    allocate.State = request.State;
                allocate.Manager = request.Manager;
                allocate.ManagerTime=DateTime.Now;


                // 更新主表记录
                int mainUpdateCount = await db.SqlSugar.Updateable(allocate)
                    .Where(x => x.AllocateId == request.AllocateId)
                    .ExecuteCommandAsync();

              

                //增加操作记录
                OperationLog log = new OperationLog()
                {
                    Operator = request.OrderCreator,
                    AllocateId = request.AllocateId,
                    OperationType = "审批",
                    OperationContent = request.Note,
                    CreateTime = DateTime.Now,
                    IsDel = false
                };
                await db.SqlSugar.Insertable(log).ExecuteReturnIdentityAsync();

                // 提交事务
                await db.SqlSugar.Ado.CommitTranAsync();

                // 设置成功返回结果
                result.Message = "审批成功";
                result.Code = APIEnum.Ok;
                result.Data = mainUpdateCount ;
                return result;
            }
            catch (Exception ex)
            {
                // 发生异常时回滚事务
                await db.SqlSugar.Ado.RollbackTranAsync();

                // 设置失败返回结果
                APIResult<int> result = new APIResult<int>();
                result.Code = APIEnum.Fail;
                result.Message = "审批失败：" + ex.Message;
                return result;
            }
        }

        
    }
}
